package x.zero.gen;

import org.beetl.sql.gen.BaseProject;
import org.beetl.sql.gen.simple.ConsoleOnlyProject;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;


/**
 * 一个Maven工程输出,代码生成输出到工程目录下

 * @see org.beetl.sql.gen.SourceConfig
 * @see org.beetl.sql.gen.SourceBuilder
 * @see ConsoleOnlyProject
 */
public class ZeroMavenProject extends BaseProject {

    String basePackage = "x.zero";

    /**
     *
     * {@inheritDoc}
     * @return  得到一个路径,对应maven工程下面的src
     */
    //Override
    @Override
    public Writer getWriterByName(String sourceBuilderName, String targetName) {
        String home = this.root;
        FileWriter writer = null;
        if(sourceBuilderName.equals("md")){
            String src = this.root+ File.separator+"src/main/resources/sql";
            String output = src+File.separator;
            checkFolder(src);
            checkFolder(output);
            try {
                writer = new FileWriter(new File(output + targetName));
            } catch (IOException e) {
                throw new IllegalArgumentException(output + targetName);
            }
        }else{

            String src = this.root+ File.separator+"src/main/java";
            String pkg = getBasePackage(sourceBuilderName);
            String subPath = pkg.replace('.',File.separatorChar);
            String output = src+File.separator+subPath+File.separator;

            checkFolder(src);
            checkFolder(output);

            try {
                writer = new FileWriter(new File(output+targetName));
            } catch (IOException e) {
                throw new IllegalArgumentException(output+targetName,e);
            }

        }
        return writer;

    }

    @Override
    public   String getBasePackage(String sourceBuilerName){
        return basePackage+"."+sourceBuilerName;
    }

    protected  void checkFolder(String file){
        new File(file).mkdirs();
    }
}
